package com.vietjetair.common;

import com.vietjetair.config.LogUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;

/**
 * @author Administrator
 */
public class ElementUtil {

    private static Logger logger = LogUtils.getCheckTicketLogger();
    private static Logger errorLogger = LogUtils.getCheckTicketErrorLogger();

    /**
     * 显示等待元素加载
     * @param driver:浏览器驱动
     * @param timeOut：等待时常
     * @param by：元素定位
     */
    public static void intelligentWait(WebDriver driver,int timeOut, final By by) {
        try {
            (new WebDriverWait(driver, timeOut)).until((ExpectedCondition<Boolean>) driver1 -> {
                WebElement element = driver1 != null ? driver1.findElement(by) : null;
                return element != null && element.isDisplayed();
            });
        } catch (TimeoutException e) {
            System.out.println("超时了 ! " + timeOut + " 秒之后还没找到元素 [" + by + "]");
            errorLogger.error(OperationCodeEnum.LOCATEFAILURE.getText() + "，预设时间：" + timeOut + " 秒之后还没找到元素 [" + by + "]");
        }
    }


    /**
     * 封装单个元素
     * @param driver 驱动
     * @param locator 定位
     * @param type 类型
     * @return 元素
     */
    public static WebElement gElement(WebDriver driver,String locator,BYCODE type) {
        //将传入字符串全部转换为小写
        if (type==BYCODE.ID) {
            System.out.println("用id查找元素" + locator);
            return driver.findElement(By.id(locator));
        } else if (type==BYCODE.XPATH) {
            System.out.println("用xpath查找元素" + locator);
            return driver.findElement(By.xpath(locator));
        } else if (type==BYCODE.NAME) {
            System.out.println("用name查找元素: " + locator);
            return driver.findElement(By.name(locator));
        } else if (type==BYCODE.CSS) {
            System.out.println("用css查找元素: " + locator);
            return driver.findElement(By.cssSelector(locator));
        } else if (type==BYCODE.CLASSNAME) {
            System.out.println("用classname查找元素: " + locator);
            return driver.findElement(By.className(locator));
        } else if (type==BYCODE.TAGNAME) {
            System.out.println("用tagname查找元素: " + locator);
            return driver.findElement(By.tagName(locator));
        } else if (type==BYCODE.LINKTEXT) {
            System.out.println("用linktext查找元素: " + locator);
            return driver.findElement(By.linkText(locator));
        } else if (type==BYCODE.PARTIALLINKTEXT) {
            System.out.println("用partiallinktext查找元素: " + locator);
            return driver.findElement(By.partialLinkText(locator));
        } else {
            System.out.println("你输入查找元素方式不支持，或属性已更改，请校验");
            return null;
        }
    }

}
